/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.sharedbills.client.welcome;

import java.util.Map;

import org.jb.sharedbills.shared.dto.WelcomeInfo;
import org.jb.sharedbills.shared.svc.EventService;
import org.jb.sharedbills.shared.svc.EventServiceAsync;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class Welcome implements EntryPoint {

	private final EventServiceAsync eventService = GWT.create(EventService.class);
	private TextBox eventDesc;
	private InlineLabel errorLabel;
	
	@Override
	public void onModuleLoad() {
		
		eventService.getWelcomeInfo( new AsyncCallback<WelcomeInfo>() {
			
			@Override
			public void onSuccess(WelcomeInfo result) {
				build(result);
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				
				
			}
		});
	}

	/**
	 * 
	 * @param welcomeInfo
	 */
	private void build( WelcomeInfo welcomeInfo ) {
		
		RootPanel.get("loading").setVisible(false);
		
		VerticalPanel panel = new VerticalPanel();
		
		if (welcomeInfo.getLoginURL() != null) {			
			StringBuilder b = new StringBuilder();
			b.append("Vous devez vous ");
			b.append( "<a href='");
			b.append( welcomeInfo.getLoginURL() );
			b.append( "'>connecter</a> pour pouvoir utiliser l'application.<br>");
			b.append( "<a href='/e?id=demo'>Cliquez-ici</a> pour une démonstration.");
			panel.add( new HTML(b.toString()) );
		} else {
			FlowPanel loginPanel = new FlowPanel();
			loginPanel.add( new InlineHTML(  welcomeInfo.getUserEmail() + " | " ) );
			loginPanel.add( new Anchor( "déconnexion", welcomeInfo.getLogoutURL() ) ); 
			RootPanel.get("login").add( loginPanel );			
		}
		
		if (welcomeInfo.getEvents().isEmpty()) {
			//panel.add( new HTML("Aucun évenement crée"));
		} else {
			for( Map.Entry<String, String> entry : welcomeInfo.getEvents().entrySet() ) {
				
				Anchor a = new Anchor( entry.getValue(), GWT.getHostPageBaseURL() + "e?id=" + entry.getKey() );
				panel.add( a );
				
			}
		}
		
		if (welcomeInfo.getLoginURL() == null) {
			
			HorizontalPanel createPanel = new HorizontalPanel();
			createPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
			createPanel.add( new InlineLabel("Ajouter un nouvel évenement : ") );
			eventDesc = new TextBox();
			eventDesc.addKeyDownHandler( new KeyDownHandler() {
				
				@Override
				public void onKeyDown(KeyDownEvent event) {
					if (event.getNativeKeyCode() == 13)
						doCreateEvent();
				}
			});
			
			createPanel.add( eventDesc );
						
			Button create = new Button( "Créer");
			create.addClickHandler( new ClickHandler() {

				@Override
				public void onClick(ClickEvent event) {
					doCreateEvent();
				}
				
			} );
			createPanel.add( create );
			errorLabel = new InlineLabel("Impossible de contacter le serveur" );
			errorLabel.setStylePrimaryName("errorlabel");
			errorLabel.setVisible(false);
			createPanel.add( errorLabel );
			createPanel.setSpacing( 5 );
			panel.add( createPanel );
		}
		
		RootPanel.get("maincontent").add(panel);
	}
	
	private void doCreateEvent() {
		if (eventDesc.getValue() == null || eventDesc.getValue().isEmpty())
			return;
		
		RootPanel.get("modal").setVisible(true);
		
		eventService.createEvent( eventDesc.getValue(), new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				RootPanel.get("modal").setVisible(false);
				errorLabel.setVisible(true);
			}

			@Override
			public void onSuccess(String result) {
				Window.Location.assign( GWT.getHostPageBaseURL() + "e?id=" + result );
			}
		});
	}
}
